// import { Constant } from "../../../../../../lib/app_constant"
// import Log from "../../../../../../lib/common/Log"
// import { JL_RCSPOP } from "../../../../../../lib/lib_rcsp"
// import { rcspDeviceOpSet } from "../../../../../../lib/rcsp/RCSPDeviceManager"
// import { clone } from "../../../../../../utils/util"
import { OPAlarm, OPFile, OPDirectoryBrowse } from "../../../../../jl_lib/jl-rcsp-op/jl_op_watch_1.1.0";
import { RCSPOpAlarm, RCSPOpDirectoryBrowse, RCSPOpFile } from "../../../../../lib/rcsp-impl/rcsp";

// pages/pageAlarm/pageAlarmDetail/pageAlarmBell/index.ts
const DEBUG = true
const TAG = "pageAlarmBell"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        bells: new Array<OPAlarm.DefaultAlarmBell>(),
        onlineDevs: new Array<OPFile.SDCardBean>(),
        listFile: new Array<OPDirectoryBrowse.File>(),
        isEnd: false,
        isLoadingMore: false,
        pathFile: new Array<String>(),
        currentDevSDCardBean: OPFile.SDCardBean.prototype,//当前浏览的设备
        currentBellType: 0,//铃声类型0: 默认类型  1：设备文件类型
        currentBellDevIndex: -1,//当前铃声文件所在的存储设备
        currentBellCluster: -1,//当前铃声文件簇号
    },
    bells: new Array<OPAlarm.DefaultAlarmBell>(),
    onLineSDCardBeans: new Array<OPFile.SDCardBean>(),
    currentFile: OPDirectoryBrowse.File.prototype,
    _operaterEventCallbackFile: OPFile.OperaterEventCallbackFile.prototype,
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        RCSPOpAlarm?.getAlarmDefaultBells().then((res) => {
            this.bells = res
            this.setData({
                bells: this.bells
            })
        })
        this.getOpenerEventChannel().on('alarmBean', (data) => {
            const temp = data.data as OPAlarm.AlarmBean
            let alarmBean = this.clone(temp) as OPAlarm.AlarmBean
            let currentDevSDCardBean: OPFile.SDCardBean = new Object() as any
            let onlineDevs = new Array<OPFile.SDCardBean>()
            const sdCardBeans = RCSPOpFile?.getOnLineSdCardBeans()
            if (alarmBean.bellType == 1) {//文件类型
                sdCardBeans?.forEach(sdCardBean => {
                    if (sdCardBean.index == alarmBean.devIndex) {
                        currentDevSDCardBean = sdCardBean
                    }
                });
                this._handleStorageDevSDCardBean(currentDevSDCardBean)
                //todo 加载当前文件目录
            }
            if (sdCardBeans) {
                onlineDevs = sdCardBeans
            }
            // DEBUG && Log.d(TAG, "currentDevSDCardBean ", alarmBean)
            this.setData({
                currentBellType: alarmBean.bellType,
                currentDevSDCardBean: currentDevSDCardBean,
                currentBellCluster: alarmBean.bellCluster,
                currentBellDevIndex: alarmBean.devIndex,
                onlineDevs: onlineDevs,
            })
        })
        this._operaterEventCallbackFile = { onEvent: this._onOperaterEventFile }
        RCSPOpFile?.registerEventCallback(this._operaterEventCallbackFile)
    },
    clone(obj: Object) {
        return JSON.parse(JSON.stringify(obj))
    },
    onShow() {
    },
    onUnload() {
        const param = new OPAlarm.AuditionParam()
        param.op = 0
        param.type = 0
        param.cluster = this.data.currentBellCluster
        // RCSPOpAlarm?.auditionAlarmBell(param).then((res) => {
        // })
        if (this.isauditionAlarmBellIng) {//未试听时调用该方法暂停试听，部分设备会异常
            RCSPOpAlarm?.auditionAlarmBell(param).then((res) => {
            })
        }
        RCSPOpFile?.unregisterEventCallback(this._operaterEventCallbackFile)
    },
    onTapSelectSound(e: any) {
        const item = e.currentTarget.dataset.item
        this._auditionAlarmBell(0, item.index!!, 0, item.name)
    },
    onTapFromIndex(e: any) {
        var index = e.currentTarget.dataset.index
        this.setData({
            mSoundFrom: index
        })

    },
    //切换浏览默认
    onSwitchDefault() {
        this.setData({ currentDevSDCardBean: (new Object() as any) })
    },
    //切换浏览的存储设备
    onSwitchStorageDev(e: WechatMiniprogram.CustomEvent) {
        const sdCardBean = e.currentTarget.dataset.item
        // DEBUG && Log.d(TAG, "切换浏览的存储设备 ", sdCardBean)
        this._handleStorageDevSDCardBean(sdCardBean)
        this.setData({ currentDevSDCardBean: sdCardBean })
    },
    //切路径
    onSwitchPath(e: WechatMiniprogram.CustomEvent) {
        const index = e.currentTarget.dataset.index
        let targetPath = ""
        for (let i = 0; i <= index; i++) {
            const element = this.data.pathFile[i];
            if (i == 0) {
                targetPath += element
            } else {
                targetPath += "/" + element
            }
        }
        // DEBUG && Log.d(TAG, "切路径 ", targetPath)
        const file = RCSPOpDirectoryBrowse?.getFileByPath(targetPath)
        if (file) {
            RCSPOpDirectoryBrowse?.appendBrowse(file, 15).then(_folder => {
                this._handleFileList(_folder)
            })
        } else {
            // DEBUG && Log.d(TAG, "切路径 file 不存在 ", targetPath)
        }
    },
    //点击文件
    onClickFile(e: WechatMiniprogram.CustomEvent) {
        const index = e.currentTarget.dataset.index
        const file = this.data.listFile[index]
        if (file.isDirectory()) {
            RCSPOpDirectoryBrowse?.appendBrowse(file, 15).then(_folder => {
                this._handleFileList(_folder)
            }).catch((error) => {
                wx.showToast({ title: error, icon: "none" })
            })
        } else {
            const fileName = file.getName() ?? ""
            const lastDotIndex = fileName.lastIndexOf(".");
            const nameWithoutExt = (lastDotIndex <= 0) ? fileName : fileName.slice(0, lastDotIndex);
            this._auditionAlarmBell(1, file.getCluster()!!, file.getDevIndex()!!, nameWithoutExt)
            // 试听
            // RCSPOpDevMusic?.devMusicPlayFile(file)
        }
    },
    //加载更多
    onLoadMore(e: any) {
        if (this.data.isLoadingMore == true || this.data.isEnd == true) {
            return
        }
        this.setData({ isLoadingMore: true })
        RCSPOpDirectoryBrowse?.loadMore(this.currentFile).then(_folder => {
            this.setData({ isLoadingMore: false })
            this._handleFileList(_folder)
        })
    },
    _onOperaterEventFile(event: OPFile.OperaterEventFile) {
        if (event.type == 'onSdCardChange' && event.onSdCardChange) {
            const sdCardBeans = event.onSdCardChange.sdCardBeans
            if (sdCardBeans != undefined) {
                this._handleSDCardBeans(sdCardBeans)
            }
        }
    },
    _handleFileList(_folder: OPDirectoryBrowse.File) {
        const parents = _folder.path.split("/")
        this.currentFile = _folder
        const tempList = _folder.listFile()
        const result = new Array<OPDirectoryBrowse.File>()
        tempList?.forEach(element => {
            //@ts-ignore
            element.name = element.getName()
            //@ts-ignore
            element.isDirectoryFile = element.isDirectory()
            //@ts-ignore
            element.cluster = element.getCluster()
            result.push(element)
        });
        this.setData({ listFile: result, isEnd: _folder.isLoadFinished(), pathFile: parents })
    },
    _handleSDCardBeans(sdCardBeans: OPFile.SDCardBean[]) {
        const onlineDevs = new Array<OPFile.SDCardBean>()
        let currentStorageDevOnLine = true
        if (this.data.currentDevSDCardBean != undefined) {
            currentStorageDevOnLine = false
        }
        for (let index = 0; index < sdCardBeans.length; index++) {
            const sdCardBean = sdCardBeans[index];
            if (sdCardBean.online == true) {
                onlineDevs.push(sdCardBean)
                if (this.data.currentDevSDCardBean && sdCardBean.index == this.data.currentDevSDCardBean.index) {
                    currentStorageDevOnLine = true
                }
            }
        }
        if (currentStorageDevOnLine == false) {//当前浏览设备掉线
            this.setData({ currentDevSDCardBean: new Object() as any, isLoadingMore: false, isEnd: false })
        }
        this.setData({ onlineDevs: onlineDevs })
    },
    _handleStorageDevSDCardBean(sdCardBean: OPFile.SDCardBean | undefined) {
        if (sdCardBean) {
            const storageDevs = RCSPOpDirectoryBrowse?.getOnLineStorageDevs()
            if (storageDevs) {
                for (let index = 0; index < storageDevs.length; index++) {
                    const storageDev = storageDevs[index];
                    if (storageDev.getDevIndex() == sdCardBean.index) {
                        this._handleStorageDev(storageDev)
                        break
                    }
                }
            }
        }
    },
    _handleStorageDev(file: OPDirectoryBrowse.File | undefined) {
        if (file) {
            // rcspDeviceOpSet.OpDirectoryBrowse?.appendBrowse(file).then(_devFolder => {
            //     const rootFolder = _devFolder.listFile()?.[0]
            //     if (rootFolder) {
            //         this.currentFile = rootFolder
            //         rcspDeviceOpSet.OpDirectoryBrowse?.appendBrowse(rootFolder, 20).then(_rootFolder => {
            //             this._handleFileList(_rootFolder)
            //         })
            //     }
            // })
            RCSPOpDirectoryBrowse?.loadMore(file, 20).then(_devFolder => {
                this._handleFileList(_devFolder)
            }).catch(_e => {
                this._handleFileList(file)
            })
        }
    },
    isauditionAlarmBellIng:false,
    _auditionAlarmBell(type: number, cluster: number, devIndex: number, bellName: string | undefined) {
        const param = new OPAlarm.AuditionParam()
        param.op = 1
        param.type = type
        param.dev = devIndex
        param.cluster = cluster
        this.setData({
            currentBellCluster: cluster
        })
        RCSPOpAlarm?.auditionAlarmBell(param).then((res) => {
            if (res) {
                this.isauditionAlarmBellIng = true 
                wx.showToast({ title: "闹铃试听" })
                this.setData({
                    currentBellType: type,//铃声类型0: 默认类型  1：设备文件类型
                    currentBellDevIndex: devIndex,//当前铃声文件所在的存储设备
                    currentBellCluster: cluster,//当前铃声文件簇号
                })
                const eventChannel = this.getOpenerEventChannel()
                eventChannel.emit('bellArg', { cluster, type, devIndex, bellName });
            }
        })

    }
})